package com.yanxu.stopthreads.producerandconsumer;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 *  使用 interrupt() 中断信号的方式，正确实现 生产者、消费者停止的方式。
 */
public class ProducerAndConsumerStopWay {
    //定义一个 BlockingQueue 阻塞队列。 充当容器
    private static BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<Integer>(10);

    public static void main(String[] args) throws InterruptedException {
        //创建一个线程。生产者，启动
        Thread producer = new Thread(new MyProducer(blockingQueue));
        producer.start();

        //消费者消费（main 线程就是消费者）
        Consumer consumer = new Consumer(blockingQueue);
        while (consumer.isNeedConsume()){
            Integer take = blockingQueue.take();
            System.out.println("消费者消费了一个" + take);
            Thread.sleep(500);
        }
        System.out.println("消费者不在继续消费了!!!");
        producer.interrupt(); //通知生产者停止
    }
}

class MyProducer implements  Runnable{
    private BlockingQueue<Integer> blockingQueue;

    public MyProducer(BlockingQueue<Integer> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    public void run() {
        int num=0;
        try {
            while (true){
                blockingQueue.put(++num);
                System.out.println("生产者生产了一个!!!"+num);
                //do other thing
                Thread.sleep(50);
                //....
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            System.out.println("生产者逻辑执行完毕，生产线程结束!!!");
        }
    }
}

class MyConsumer{
    public boolean isNeedConsume(){
        Random random = new Random();
        int randomInt = random.nextInt(100);
        System.err.println("random"+randomInt);
        if (randomInt < 90) {
            return true;
        }
        return false;
    }
}